#!/usr/bin/env python3
# coding: utf-8

from flask import Flask, render_template, request
from flask_login import LoginManager, login_user, current_user
from sqlalchemy import and_
from flask_jwt_extended import create_access_token, jwt_required, JWTManager, get_jwt_identity

import hashlib

import requests
import datetime
import json
import smtplib
from email.mime.text import MIMEText
import string
import random
import time
from urllib.parse import urlencode

from table.tables import User, Device, Borrow, Borrowteam, Projectline, Bilidata, Mqtt, Data120, Arinseu
from table.database import DataBase, Session, db_engine

from scripts import tencentCloud

app = Flask(__name__,
            static_url_path='/static',  # 配置静态文件的访问 url 前缀
            static_folder='./dist/static',  # 配置静态文件的文件夹
            template_folder='./dist/templates'
            )
# template_folder='../xxxx' 指 前端文件的目录
# static_folder="../xxxx"  指 静态文件的目录
login_manager = LoginManager(app)
login_manager.login_view = 'login'
login_manager.session_protection = 'strong'
app.config['SECRET_KEY'] = '123qweasdzxc'

app.config['JWT_SECRET_KEY'] = 'super-secret'
jwt = JWTManager(app)

DataBase.metadata.create_all(db_engine)

soundclass = ["大自然声音","人物声音","学习、生活声音","运动声音","文化社团声音","东大历史声音","其他"]

def emailFindBackGetNum(email):
    # 设置服务器所需信息
    # 163邮箱服务器地址
    mail_host = 'smtp.qq.com'
    # 163用户名
    mail_user = '1779176477@qq.com'
    # 密码(部分邮箱为授权码)
    mail_pass = 'ruvamobemaehbaii'
    # 邮件发送方邮箱地址
    sender = '1779176477@qq.com'
    title = '东南大学B站官方'
    # 生成6位随机验证码
    randomnum = "".join(random.sample([x for x in string.ascii_letters + string.digits], 6))
    email_content = '请输入该验证码验证邮箱：' + randomnum
    # 邮件接受方邮箱地址，注意需要[]包裹，这意味着你可以写多个邮件地址群发
    sendemail(email, title, email_content, mail_host, mail_user, mail_pass, sender)
    return randomnum


def sendemail(rec, title, con, mail_host, mail_user, mail_pass, sender):
    receivers = rec
    # 设置email信息，邮件内容设置
    message = MIMEText(con, 'plain', 'utf-8')
    # 邮件主题
    message['Subject'] = title
    # 发送方信息
    message['From'] = sender
    # 接受方信息
    message['To'] = receivers[0]

    # 登录并发送邮件
    try:
        smtpobj = smtplib.SMTP_SSL(mail_host)
        # 连接到服务器
        smtpobj.connect(mail_host, 465)
        # 登录到服务器
        smtpobj.login(mail_user, mail_pass)
        # 发送
        smtpobj.sendmail(sender, receivers, message.as_string())
        # 退出
        smtpobj.quit()
    except smtplib.SMTPException as e:
        print('error', e)  # 打印错误


@login_manager.user_loader
def load_user(user_name):
    session = Session()
    return session.query(User).filter_by(username=user_name).first()


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/dashboard')
@jwt_required()
def dashboard():
    return render_template('dashboard.html')


@app.route('/dashboard_admin')
def dashboard_admin():
    return render_template('dashboard_admin.html')


def getOpenid(code):
    params = {'appid': 'wx17e720866263d04a', 'secret': 'a186e1cd1f656dfd511cef9cb00ac066', 'js_code': code, 'grant_type': 'authorization_code'}
    print('https://api.weixin.qq.com/sns/jscode2session?' + urlencode(params))
    url = 'https://api.weixin.qq.com/sns/jscode2session?' + urlencode(params)
    response = requests.get(url)
    content = json.loads(response.content)
    print(content)
    if content['openid']:
        openid = content['openid']
    return openid

@app.route('/authorize', methods=['POST'])
def authorize():
    get_data = request.get_json(silent=True)
    code = get_data['code']
    openid = getOpenid(code)


    session = Session()
    user = session.query(User).filter_by(openid=openid).first()
    if user: # 认证成功，说明绑定微信登陆信息了,此时需要更新用户的token
        print("认证成功")
        access_token = create_access_token(identity=user.username)
        return json.dumps({'success': True, "token": access_token})
    else:
        print("认证失败")
        return json.dumps({'success': False, "openid": openid})
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        get_data = request.get_json(silent=True)
        username = get_data['username']
        password = get_data['password']
        passwordMd5=hashlib.md5(password.encode(encoding='utf-8')).hexdigest()
        try:
            openid = get_data['openid']
        except:
            openid = None
        print(username, password, openid)
        session = Session()
        user = session.query(User).filter_by(username=username, password=passwordMd5).first()
        if user:
            access_token = create_access_token(identity=username)
            session.query(User).filter_by(username=username).update({"openid": openid})
            session.commit()
            login_user(user)
            if user.role == "member":
                print("社员登录")
                return json.dumps({'success': True, 'msg': "登录成功，跳转中...", 'nexturl': '/dashboard', 'access_token': access_token})
            elif user.role == "admin":
                print("管理员登录")
                return json.dumps({'success': True, 'msg': "登录成功，跳转中...", 'nexturl': '/dashboard_admin', 'access_token': access_token})
        else:
            print("失败")
            return json.dumps({'success': False, 'msg': "登录失败，请联系管理员"})
    else:
        return render_template('index.html')


@app.route('/logout', methods=['POST'])
@jwt_required()
def logout():
    session = Session()
    username = get_jwt_identity()
    session.query(User).filter_by(username=username).update({"openid": ""})
    session.commit()
    return json.dumps({'nexturl': '/', 'success': True})


###############  GET  #################

# 获取校验码
@app.route('/verification')
def verification():
    verification = request.args.get('verification')
    if verification == 'bilibiliseu2022':
        return json.dumps({'success': True})
    else:
        return json.dumps({'success': False})

# 获取邮箱验证码


@app.route('/getverify', methods=['POST'])
def getverify():
    get_data = request.get_json(silent=True)
    username = get_data['username']
    session = Session()
    record = session.query(User).filter_by(username=username).first()
    if record == None:  # 没有这个用户
        return json.dumps({'success': False})
    else:
        if record.email == None or record.email == '':
            email = username + "@seu.edu.cn"
        else:
            email = record.email
        msg = "验证码已发送至%s，请查收哦~" % (email)
        verifycode = emailFindBackGetNum(email)
        session.query(User).filter(User.username == username).update({'verifycode': verifycode})
        session.commit()
        return json.dumps({'success': True, 'msg': msg})


@app.route('/getbilibili', methods=['GET'])
def getbilibili():
    url = 'https://api.bilibili.com/x/web-interface/card?mid=36964670&jsonp=jsonp&article=true'
    res = requests.get(url)
    res = json.loads(res.content)
    follower = res["data"]["follower"]
    like_num = res["data"]["like_num"]
    # follower = 5600
    # like_num = 11300
    date = datetime.datetime.now().strftime("%Y-%m-%d")  # 获取当前时间
    session = Session()
    # 获取最大ID
    record = session.query(Bilidata).order_by(Bilidata.id.desc()).first()
    id = 1
    if record != None:
        if date > record.time:
            id = record.id + 1
            data = Bilidata(id=id, time=date, follow=follower, likenum=like_num)
            session.add(data)
            session.commit()
    else:
        data = Bilidata(id=id, time=date, follow=follower, likenum=like_num)
        session.add(data)
        session.commit()

    # 返回前端数据
    data_follow = []
    data_likenum = []
    categories = []
    series = [{
        "name": "粉丝数",
        "data": [],
        "color": '#fa7a63'
    },{
        "name": "点赞数",
        "data": [],
        "color": '#5b98fa'
    }]
    records = session.query(Bilidata).all()
    for record in records:
        categories.append(record.time)
        data_follow.append(record.follow)
        data_likenum.append(record.likenum)
    series[0]["data"] = data_follow
    series[1]["data"] = data_likenum
    follow = {
        "categories": categories,
        "series": [series[0]]
    }
    likenum = {
        "categories": categories,
        "series": [series[1]]
    }
    print(follow)
    return json.dumps({'follow': follow, 'likenum': likenum})


@app.route('/getuser', methods=['get'])
@jwt_required()
def getuser():
    session = Session()
    username = get_jwt_identity()
    current_user = session.query(User).filter_by(username=username).first()
    record = session.query(User).filter_by(username = current_user.username).first()
    data = {'name': record.name, 'username': record.username, 'group': record.group, 'uid': record.uid, 'studentnum': record.studentnum, 'password': record.password, 'email': record.email, 'avatar': record.avatar}
    return json.dumps(data)


@app.route('/getuserall', methods=['get'])
@jwt_required()
def getuserall():
    session = Session()
    users = []
    records = session.query(User).all()
    for record in records:
        if record.role == "member":
            users.append({
                "label": record.name,
                "value": record.name
            })
    return json.dumps(users)


@app.route('/getdevice', methods=['get'])
@jwt_required()
def getdevice():
    session = Session()
    records = session.query(Device).order_by(Device.serial).all()
    data = []
    if records != None:
        for record in records:
            data.append({'id': record.id, 'serial': record.serial, 'devicename': record.devicename, 'devicetype': record.devicetype,
                         'amount': record.amount, 'remain': record.remain, 'detail': record.detail, 'notice': record.notice, 'imgurl': record.imgurl})
        # print(data)
    return json.dumps(data)

@app.route('/getdeviceinfo', methods=['get'])
@jwt_required()
def getdeviceInfo():
    session = Session()
    deviceId=request.args.get("id")
    print("id",deviceId)
    record = session.query(Device).filter_by(id=deviceId).first()
    print("record",record)
    data={'id': record.id, 'serial': record.serial, 'devicename': record.devicename, 'devicetype': record.devicetype,
                         'amount': record.amount, 'remain': record.remain, 'detail': record.detail, 'notice': record.notice}
    return json.dumps(data)

@app.route('/getborrow', methods=['get'])
@jwt_required()
def getborrow():
    session = Session()
    username = get_jwt_identity()
    current_user = session.query(User).filter_by(username=username).first()
    records = session.query(Borrow).filter_by(borrowuser = current_user.name).order_by(Borrow.borrowtime.desc()).all()
    data = []
    if records != None:
        for record in records:
            device = session.query(Device).filter_by(id = record.deviceid).first()
            if device != None:
                data.append({'id': record.id, 'serial': device.serial, 'devicename': device.devicename, 'devicetype': device.devicetype,
                             'borrownum': record.borrownum, 'borrowtime': record.borrowtime, 'keepdays': record.keepdays, 'returntime': record.returntime, 'returnuser': record.returnuser, 'isreturn': record.isreturn})
        # print(data)
    return json.dumps(data)

@app.route('/getborrowById', methods=['get'])
@jwt_required()
def getborrowById():
    session = Session()
    borrowId = request.args.get("id")
    record = session.query(Borrow).filter_by(id = borrowId).first()
    device = session.query(Device).filter_by(id=record.deviceid).first()
    data = {'id': record.id, 'serial': device.serial, 'devicename': device.devicename, 'devicetype': device.devicetype,
            'borrownum': record.borrownum, 'borrowtime': record.borrowtime, 'keepdays': record.keepdays,
            'returntime': record.returntime, 'returnuser': record.returnuser, 'isreturn': record.isreturn}
    return json.dumps(data)

@app.route('/getActiveItem', methods=['get'])
@jwt_required()
def getActivateItem():
    session = Session()
    activateItem = session.query(Borrowteam).filter_by(isreturn="false").first()

    if activateItem!=None:
        userId = get_jwt_identity()
        current_user = session.query(User).filter_by(username=userId).first()
        username = current_user.name
        print("username",username, activateItem.creator,activateItem.to_dict())
        response={
            "itemGoing": 1,
            "data":activateItem.to_dict(),
            "isCreator":username == activateItem.creator
        }
    else:
        response={
            "itemGoing": 0
        }
    return json.dumps(response)

#应该不需要了
@app.route('/getborrowteam', methods=['get'])
@jwt_required()
def getborrowteam():
    session = Session()
    username = get_jwt_identity()
    current_user = session.query(User).filter_by(username=username).first()
    recordId = [] # 记录已经加载的借用记录id

    # 总负责人是自己的记录
    records = session.query(Borrowteam).filter_by(responseuser = current_user.name).all()
    id = 1
    data = []
    activitycodelist = []
    if records != None:
        for record in records:
            recordId.append(record.id)
            device = session.query(Device).filter_by(id=record.deviceid).first()
            if device != None:
                datatmp = {'deviceid': record.deviceid,'serial': device.serial, 'devicename': device.devicename,
                             'devicetype': device.devicetype,
                             'borrownum': record.borrownum, 'deviceresponseuser': record.deviceresponseuser,
                             'keepdays': record.keepdays, 'note': record.note, 'returntime': record.returntime,
                             'returnuser': record.returnuser, 'isreturn': record.isreturn}
            if record.activitycode not in activitycodelist:
                activitycodelist.append(record.activitycode)
                data.append({
                    "id": id,
                    "activitycode": record.activitycode,
                    "responseuser": record.responseuser,
		            "borrowtime": record.borrowtime,
                    "content": [datatmp]
                })
                id = id + 1
            else:
                data[activitycodelist.index(record.activitycode)]["content"].append(datatmp)
        # print(data)

    # 总负责人不是自己但是自己是器材负责人
    records = session.query(Borrowteam).filter_by(deviceresponseuser = current_user.name).all()
    if records is not None:
        for record in records:
            if record.activitycode not in activitycodelist: # 前面没有加载的
                activityrecords = session.query(Borrowteam).filter_by(activitycode = record.activitycode).all() # 获取该活动所有记录
                for activityrecord in activityrecords:
                    device = session.query(Device).filter_by(id=activityrecord.deviceid).first()
                    if device != None:
                        datatmp = {'deviceid': activityrecord.deviceid,'serial': device.serial, 'devicename': device.devicename,
                                   'devicetype': device.devicetype,
                                   'borrownum': activityrecord.borrownum, 'deviceresponseuser': activityrecord.deviceresponseuser,
                                   'keepdays': activityrecord.keepdays, 'note': activityrecord.note, 'returntime': activityrecord.returntime,
                                   'returnuser': activityrecord.returnuser, 'isreturn': activityrecord.isreturn}
                    if activityrecord.activitycode not in activitycodelist:
                        activitycodelist.append(activityrecord.activitycode)
                        data.append({
                            "id": id,
                            "activitycode": activityrecord.activitycode,
                            "responseuser": activityrecord.responseuser,
                            "borrowtime": activityrecord.borrowtime,
                            "content": [datatmp]
                        })
                        id = id + 1
                    else:
                        data[activitycodelist.index(activityrecord.activitycode)]["content"].append(datatmp)
    # print(data)
    return json.dumps(data)


@app.route('/getborrowData', methods=['get'])
@jwt_required()
def getborrowData():
    session = Session()
    data = []

    # 先查个人借用
    records = session.query(Borrow).filter_by(isreturn = "false").all()
    if records is not None:
        for record in records:
            data.append({
                'deviceid': record.deviceid,
                'borrowuser': record.borrowuser,
                'borrowtime': record.borrowtime,
                'borrownum': record.borrownum,
                'keepdays': record.keepdays
            })

    # 再查集体借用
    records = session.query(Borrowteam).filter_by(isreturn="false").all()
    if records is not None:
        for record in records:
            data.append({
                'deviceid': record.deviceid,
                'borrowuser': record.deviceresponseuser,
                'borrowtime': record.borrowtime,
                'borrownum': record.borrownum,
                'keepdays': record.keepdays
            })

    return json.dumps(data)


@app.route('/getprojectline', methods=['get'])
@jwt_required()
def getprojectline():
    session = Session()
    data = []
    option = []
    series = []
    xAxisData = []
    projectname = ''
    # 先查个人借用
    records = session.query(Projectline).filter_by(projectname = "摆烂者").all()
    if records is not None:
        for record in records:
            data.append({
                'value': record.pointemo,
                'name': record.pointname
            })
            xAxisData.append(record.pointtime)
            projectname = record.projectname


    series.append({
        'name': projectname,
        'type': "line",
        'smooth': True,
        'data': data
    })
    option.append({
        'title': {
            'text': projectname,
            'left': "center"
        },
        'xAxis': {
            'type': 'category',
            'data': xAxisData
        },
        'series': series
    })
    return json.dumps(option)


@app.route('/getmqtt', methods=['get'])
@jwt_required()
def getmqtt():
    session = Session()
    data = []
    # 查询数据库最新的数据
    temp = session.query(Mqtt).order_by(Mqtt.id.desc()).filter_by(name = "Temp").first().value
    wet = session.query(Mqtt).order_by(Mqtt.id.desc()).filter_by(name = "Hum").first().value
    nitu = session.query(Mqtt).order_by(Mqtt.id.desc()).filter_by(name = "AO").first().value
    # print("温度："+temp)
    # print("湿度："+wet)
    # print("土壤湿度："+nitu)
    if int(nitu) > 1000:
        nitumax = 1200
    else:
        nitumax = 800

    return json.dumps({'temp':temp, 'wet':wet, 'nitu':nitu,'tempmax':60,'wetmax':100,'nitumax':nitumax})


@app.route('/get120', methods=['get'])
@jwt_required()
def get120():
    session = Session()
    data = []
    records = session.query(Data120).order_by(Data120.id.desc()).all()
    if records != None:
        for record in records:
            if record.likeauthor == None:
                islike = False
            else:
                islike = current_user.name in record.likeauthor.split('#')
            if record.unlikeauthor == None:
                isunlike = False
            else:
                isunlike = current_user.name in record.unlikeauthor.split('#')
            data.append({
                "id": record.id,
                "title": record.title,
                "detail": record.detail,
                "classify": record.classify,
                "author": record.author,
                "like": record.like,
                "unlike": record.unlike,
                "islike": islike,
                "isunlike": isunlike
            })
    return json.dumps({'data':data, "soundclass": soundclass})


@app.route('/getarinseu', methods=['get'])
@jwt_required()
def getArinSeu():
    url = 'http://121.248.51.243:9120/sc_status'
    res = requests.get(url)
    server = res.content.decode('UTF-8').split('\n')[2]
    server = int(server.split(' ')[1])
    session = Session()
    self = session.query(Arinseu).first().self
    self = self +1
    download = server - self
    session.query(Arinseu).filter(Arinseu.id == 1).update({'self': self, 'download': download})
    session.commit()
    data = download
    return json.dumps({'data': data})


###############  POST  #################
@app.route('/signin', methods=['POST'])
def signin():
    session = Session()
    print(request.get_json(silent=True))
    get_data = request.get_json(silent=True)['form']
    print(get_data["card"])
    # 查看是否已经注册
    record = session.query(User).filter_by(username=get_data["card"]).first()
    if record is not None:
        print(record.username)
        return json.dumps({'success': False, 'msg': "该账号已注册，请勿重复注册"})

    record = session.query(User).order_by(User.id.desc()).first()
    id = 1
    if record != None:
        id = record.id + 1
    passwordMd5 = hashlib.md5(get_data["password"].encode(encoding='utf-8')).hexdigest()
    data=User(id=id, password=passwordMd5, username=get_data["card"], studentnum=get_data["studentnum"],
                          name=get_data["name"], group=get_data["group"], uid=get_data["uid"], email=get_data["email"])
    session.add(data)
    session.commit()
    return json.dumps({'success': True, 'msg': "注册成功！现在去登陆吧！"})


@app.route('/updateuser', methods=['POST'])
@jwt_required()
def updateuser():
    session = Session()
    username = get_jwt_identity()
    current_user = session.query(User).filter_by(username=username).first()
    get_data = request.get_json(silent=True)
    print(get_data)
    session.query(User).filter(User.username == current_user.username).update({get_data["field"]: get_data["value"]})
    session.commit()
    return json.dumps({'success': True, 'msg': get_data["field"] + "修改成功！"})


@app.route('/updatedevice', methods=['POST'])
@jwt_required()
def updatedevice():
    session = Session()
    get_data = request.get_json(silent=True)
    records = session.query(Device).all()
    if records != None:
        for record in records:
            session.delete(record)
        session.commit()
    data = []
    for index, item in enumerate(get_data):
        data.append(
            Device(id=index + 1, serial=item["serial"], devicename=item["devicename"], devicetype=item["devicetype"],
                   amount=item["amount"], remain=item["remain"]))
    session.add_all(data)
    session.commit()
    return json.dumps({"success": True})


@app.route('/newborrow', methods=['POST'])
@jwt_required()
def newborrow():
    session = Session()
    username = get_jwt_identity()
    current_user = session.query(User).filter_by(username=username).first()
    get_data = request.get_json(silent=True)["data"] # 获取前端数据
    keepdays = get_data["keepdays"]
    if len(keepdays.split("T")) > 1:
        keepdays = keepdays.split("T")[0] + " " + keepdays.split("T")[1].split(".")[0]
    borrowtime = get_data["borrowtime"]
    if len(borrowtime.split("T")) > 1:
        borrowtime = borrowtime.split("T")[0] + " " + borrowtime.split("T")[1].split(".")[0]
    # 获取最大ID
    record = session.query(Borrow).order_by(Borrow.id.desc()).first()
    id = 1
    if record != None:
        id = record.id + 1

    date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") # 获取当前时间

    # 更改设备数据库余量
    record = session.query(Device).filter(Device.id == get_data["id"])
    if record != None:
        record.update({"remain": record.first().remain - get_data["borrownum"]})
    # 新增记录
    data = Borrow(id=id, borrowuser=current_user.name, deviceid=get_data["id"], operatetime = date, borrownum=get_data["borrownum"],
                borrowtime=borrowtime, keepdays=keepdays)
    session.add(data)
    session.commit()
    return json.dumps({'success': True})


@app.route('/newborrowteam', methods=['POST'])
@jwt_required()
def newborrowteam():
    session = Session()
    get_data = request.get_json(silent=True)["data"]# 获取前端数据
    userId = get_jwt_identity()
    current_user = session.query(User).filter_by(username=userId).first()
    username = current_user.name
    activitycode = get_data["activitycode"]
    responseuser = get_data["responseuser"]
    expectReturnTime = get_data["expectReturnTime"]
    borrowtime = get_data["borrowtime"]
    if len(expectReturnTime.split("T")) > 1:
        expectReturnTime = expectReturnTime.split("T")[0] + " " + expectReturnTime.split("T")[1].split(".")[0]
    if len(borrowtime.split("T")) > 1:
        borrowtime = borrowtime.split("T")[0] + " " + borrowtime.split("T")[1].split(".")[0]

    date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")  # 获取当前时间
    # 获取最大ID
    record = session.query(Borrowteam).order_by(Borrowteam.id.desc()).first()
    borrowTeamId = 1
    if record != None:
        borrowTeamId = record.id + 1
    # 获取borrow最大id
    record = session.query(Borrow).order_by(Borrow.id.desc()).first()
    borrowId = 1
    if record != None:
        borrowId = record.id + 1

    # 新增记录
    deviceRecords = session.query(Device).all()
    data = Borrowteam(id=borrowTeamId, activitycode=activitycode, operatetime=date, responseuser=responseuser,
                      borrowtime=borrowtime, expectReturnTime=expectReturnTime, note=get_data["note"],description=get_data["description"],
                      coverUrl=get_data["coverUrl"],creator=username)
    session.add(data)
    session.commit()
    for device in deviceRecords:
        # 更改设备数据库余量
        borrowNum=device.remain
        device.remain=0

        # 新增记录
        data = Borrow(id=borrowId, borrowuser=activitycode, deviceid=device.id, operatetime=date,
                      borrownum=borrowNum,borrowtime=borrowtime, keepdays=expectReturnTime)
        session.add(data)
        session.commit()
        borrowId+=1

    return json.dumps({'success': True})

@app.route('/devicereturn', methods=['POST'])
@jwt_required()
def devicereturn():
    session = Session()
    username = get_jwt_identity()
    current_user = session.query(User).filter_by(username=username).first()
    get_data = request.get_json(silent=True)["data"] # 获取前端数据
    date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") # 获取当前时间
    print(get_data["id"])
    # 获取归还的表格信息
    record = session.query(Borrow).filter(Borrow.id == get_data["id"])
    if record != None:
        # 更改设备数据库余量
        print(record.first().deviceid)
        device = session.query(Device).filter(Device.id == record.first().deviceid)
        if device != None:
            device.update({"remain": device.first().remain + record.first().borrownum})
        # 更改借用数据库状态
        record.update({"returntime": date, "returnuser": current_user.name, "isreturn": "true"})
        session.commit()

    return json.dumps({'success': True})

@app.route('/renewborrow', methods=['POST'])
@jwt_required()
def renewborrow():
    session = Session()
    get_data = request.get_json(silent=True)["data"] # 获取前端数据
    renewDay=get_data["renewDay"]
    date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") # 获取当前时间
    if len(renewDay.split("T")) > 1:
        renewDay = renewDay.split("T")[0] + " " + renewDay.split("T")[1].split(".")[0]
    # 获取归还的表格信息
    record = session.query(Borrow).filter(Borrow.id == get_data["id"])
    if record != None:
        # 更改借用数据库状态
        record.update({"keepdays": renewDay,"operatetime":date})
        session.commit()
    return json.dumps({'success': True})

@app.route('/teamdevicereturn', methods=['POST'])
@jwt_required()
def teamdevicereturn():
    session = Session()
    print(request.get_json(silent=True))
    id = request.get_json(silent=True)["id"]
    date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")  # 获取当前时间
    userId = get_jwt_identity()
    current_user = session.query(User).filter_by(username=userId).first()
    username = current_user.name
    # 更新Borrowteam
    item = session.query(Borrowteam).filter_by(id=id).first()
    activitycode=item.activitycode
    item.returntime=date
    item.operatetime=date
    item.isreturn="true"
    session.commit()
    # 获取归还的表格信息
    recordList = session.query(Borrow).filter(Borrow.borrowuser == activitycode) .all()
    for record in recordList:
        # 更改设备数据库余量
        device = session.query(Device).filter(Device.id == record.deviceid)
        if device.first() != None:
            device.update({"remain": device.first().remain + record.borrownum})
        # 更改借用数据库状态
        record.returntime=date
        record.returnuser=username
        record.isreturn="true"
        session.commit()
    return json.dumps({'success': True})


@app.route('/updatepassword', methods=['POST'])
def updatepassword():
    get_data = request.get_json(silent=True)
    username = get_data['username']
    password = get_data['password']
    passwordMd5 = hashlib.md5(password.encode(encoding='utf-8')).hexdigest()
    verifycode = get_data['verifycode']
    print(username, password, verifycode)
    session = Session()
    record = session.query(User).filter_by(username=username).first()
    print(record.verifycode)
    if record == None:  # 没有这个用户
        return json.dumps({'success': False})
    else:
        if verifycode == record.verifycode:  # 验证成功
            session.query(User).filter(User.username == username).update({'password': passwordMd5})
            session.commit()
            return json.dumps({'success': True})
        else:
            return json.dumps({'success': False})


@app.route('/120like', methods=['POST'])
def like120():
    get_data = request.get_json(silent=True)
    id = get_data['id']
    session = Session()
    likeauthor = session.query(Data120).filter_by(id=id).first().likeauthor
    if likeauthor == None:
        likeauthor = ''
    if current_user.name in likeauthor.split('#'):
        like = session.query(Data120).filter_by(id=id).first().like - 1
        items = likeauthor.split('#')
        items.remove(current_user.name)
        items.remove('')
        likeauthortmp = ""
        for item in items:
            likeauthortmp = likeauthortmp + '#' + item
        session.query(Data120).filter(Data120.id == id).update({'like': int(like), 'likeauthor': likeauthortmp})
    else:
        like = session.query(Data120).filter_by(id = id).first().like + 1
        likeauthor = likeauthor + "#" + current_user.name
        session.query(Data120).filter(Data120.id == id).update({'like': int(like), 'likeauthor': likeauthor})
    session.commit()
    return json.dumps({'success': 'True'})


@app.route('/120unlike', methods=['POST'])
def likeun120():
    get_data = request.get_json(silent=True)
    id = get_data['id']
    session = Session()
    unlikeauthor = session.query(Data120).filter_by(id = id).first().unlikeauthor
    if unlikeauthor == None:
        unlikeauthor = ''
    print(unlikeauthor)
    if current_user.name in unlikeauthor.split('#'):
        unlike = session.query(Data120).filter_by(id=id).first().unlike - 1
        items = unlikeauthor.split('#')
        print(items)
        items.remove(current_user.name)
        items.remove('')
        print(items)
        unlikeauthortmp = ""
        for item in items:
            unlikeauthortmp = unlikeauthortmp + item + '#'
        session.query(Data120).filter(Data120.id == id).update({'unlike': int(unlike), 'unlikeauthor': unlikeauthortmp})
    else:
        unlike = session.query(Data120).filter_by(id = id).first().unlike + 1
        unlikeauthor = unlikeauthor + current_user.name + "#"
        session.query(Data120).filter(Data120.id == id).update({'unlike': int(unlike), 'unlikeauthor': unlikeauthor})
    session.commit()
    return json.dumps({'success': 'True'})


@app.route('/add120', methods=['POST'])
def add120():
    session = Session()
    get_data = request.get_json(silent=True)
    form = get_data['form']
    title = form["title"]
    detail = form["detail"]
    value = form["value"]
    id = str(int(round(time.time() * 1000)))
    print(id)
    classify = soundclass[int(value)]
    author = current_user.name
    data = Data120(id=id, title=title, detail=detail, classify=classify,author=author)
    session.add(data)
    session.commit()
    return json.dumps({'success': 'True'})


@app.route('/gettmpkeys', methods=['GET'])
@jwt_required()
def gettmpkeys():
    return tencentCloud.get_credential_demo()


@app.route('/getDeviceBorrowDetail', methods=['POST'])
@jwt_required()
def getDeviceBorrowDetail():
    session = Session()
    get_data = request.get_json(silent=True)
    id = str(get_data['id'])
    print(id,type(id))
    # 筛选record中borrowtime大于当前时间的记录，并且isreturn为false的记录
    record = session.query(Borrow).filter(and_(Borrow.deviceid == id, Borrow.isreturn == 'false')).all()
    device = session.query(Device).filter(Device.id == id).first()
    if record == None:
        return json.dumps({'success': False})
    else:
        # 格式化record中borrowtime为时间戳,并筛选出时间大于当前时间的记录
        # record = [item for item in record if time.mktime(time.strptime(item.keepdays, "%Y-%m-%d %H:%M:%S")) > time.time()]
        return json.dumps({'success': True, 'data': [item.to_dict() for item in record], 'device': device.to_dict()})




if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
    # app.run()
